<script setup lang="ts">
import { ref } from 'vue'
import {useRouter} from "vue-router";
import axios from "axios";
const router = useRouter()
const username = ref('');
const password = ref('');

//登录方法
const handleLogin = async () => {
  try {
    const res = await axios.post(
        "/AppStore/user/login",
        {
          username: username.value,
          password: password.value
        }
    );

    const { code, message, data } = res.data;
    if (code === 200) {
      // 登录成功
      localStorage.setItem('userInfo', JSON.stringify(data));
      const userInfoStr = localStorage.getItem('userInfo'); // 获取登录信息
      if (userInfoStr) {
        const userInfo = JSON.parse(userInfoStr); // 解析为对象
        const userId = userInfo.id; // 提取用户ID
        alert('登录成功！');
        // 跳转用户页面
        await router.push({path:'/',query:{userId}});
      }
    } else {
      // 登录失败：提示错误
      alert(message);
    }
  } catch (error) {
    console.error('登录请求失败:', error);
    alert('网络异常，请重试');
  }
};
const handleRegister = async () => {
  try {
    const res = await axios.post(
        '/AppStore/user/register',
        { username: username.value, password: password.value }
    );
    if (res.data.code === 200) {
      alert('注册成功！请登录');
      username.value = '';
      password.value = '';
    } else {
      alert(res.data.message);
    }
  } catch (error) {
    alert('网络异常，请重试');
  }
};
</script>

<template>
  <div class = "signView">
    <div style = "font-size: 20px; font-weight: bold;margin-top: 50%;margin-bottom: 20px ">AppStore 登录界面</div>
    <span style = "margin-bottom: 10px">
      用户名:
      <el-input v-model="username" style="width: 240px" placeholder="请输入用户名" />
    </span>
    <span>
      密码：
      <el-input
          v-model="password"
          style="width: 240px"
          type="password"
          placeholder="请输入密码"
          show-password
      />
    </span>
    <span style = "display: flex;">
    <button @click = "handleRegister" style = "font-size: 15px;margin-top:10px;margin-right: 30px;margin-left: 100px;">注册</button>

    <button @click="handleLogin" style = "font-size: 15px;margin-top:10px;margin-right: 30px ">登录</button>

    </span>
  </div>

</template>

<style scoped>
.signView{
  display: flex;
  flex-direction: column;
  justify-items: center;
  align-items: center;
  min-height: 100vh;
  background: #f2f2f2;
  max-width: 420px;
  margin: 0 auto;
  padding: 0 16px;
}
</style>